package com.db.controller;

import com.db.entity.Person;
import com.db.service.PersonService;
import com.db.service.impl.PersonServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/showPersons")
public class ShowPersonsController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        PersonService ps = new PersonServiceImpl();
        Integer pageIndex = 1;

        String str = request.getParameter("pageIndex");
        if(str != null)pageIndex = Integer.parseInt(str);
        request.setAttribute("pageIndex",pageIndex);

        Integer userid = (Integer) request.getSession().getAttribute("userid");


        List<Person> list = ps.retrieveLimit(pageIndex,userid);
        HttpSession session = request.getSession();

        session.setAttribute("value",null);
        session.setAttribute("type",null);

        String username = (String)session.getAttribute("login");
        if( username == null){
            response.sendRedirect(request.getContextPath()+"/login.jsp ");
            return;
        }
        request.setAttribute("Persons",list);
        Integer maxpage = 0;
        List<Person> list1 = ps.RetrieveAll(userid);
        if (list1.size()%5==0) {
            maxpage =list1.size()/5;
        }else{
            maxpage = list1.size()/5+1;
        }
        request.setAttribute("maxPage",maxpage);
        request.getRequestDispatcher("/showAllPerson.jsp").forward(request,response);
    }
}
